/*
 * DA03.c
 *
 * Created: 3/25/2014 10:19:16 AM
 *  Author: mummm2
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>		//used for interrupts

int main(void)
{	
	//initialize all variables and registers needed
	DDRB = 0xff;	//Port B is all output
	DDRC = 0xff;	//Port C is all output
	DDRD = 0x00;	//Port D is all input
	//enable interrupts on t1, enable OutputCompareA interrupt
	TIMSK1 = (1<<ICIE1) | (1<<OCIE1A) | (0<<TOIE1); 
	sei();			//enable interrupts
	OCR1A = 0x1E84;	//set compare match A1 for timer1
	TCCR0B = 0b00000110; //External Clock source on T0 pin, falling edge
	TCCR1A = (0<<WGM11) | (0<<WGM10);	//CTC
	TCCR1B = (0<<WGM13) | (1<<WGM12) | (1<<CS12) | (0<<CS11) | (0<<CS10);  //N=256
	
	//Infinite loop, TCNT1 will never reach 0xFFFF
	while(TCNT1 <= 65535){
		if(TCNT1 == 65534)
			TCNT1 = 0;
	}
}

/*
Every falling edge of timer1, increment timer0
Every 16th falling edge of timer1 will toggle pin9
*/
ISR(TIMER1_COMPA_vect){
	PORTC ^= (1<<2); 	//toggle PC2, which is physically connected to T0, increment timer0 on falling edge
	PORTB = TCNT0;		//display current value of timer0
	if(TCNT0 % 16 == 0) {		//check if 16th time
		PORTC ^= (1<<0);	//toggle PC0, LEDBarPin9
	}
}
